package com.dingup.paike.aop.pk;

import com.alibaba.fastjson.JSON;
import com.dingup.api.Util.LoggerUtil;
import com.dingup.api.bean.feign.log.LogSaveFeignBean;
import com.dingup.api.enums.log.LogModelEnum;
import com.dingup.api.enums.log.LogUpdateTypeEnum;
import com.dingup.api.enums.log.PkLessonLogEnum;
import com.dingup.paike.adapter.pk.PkLessonUpdateLogAdapter;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoRequestBean;
import com.dingup.paike.dao.PkLessonInfoMapper;
import com.dingup.paike.feign.client.log.LogFeignClient;
import com.dingup.paike.feign.client.user.UserFeignClient;
import com.dingup.paike.model.pk.PkLessonInfo;
import com.dingup.paike.model.pk.PkLessonUser;
import com.dingup.paike.util.PkLoggerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/8/29.
 */
@Component
@Aspect
public class PkLessonInfoLogAop {

    private static Logger logger = LoggerFactory.getLogger(PkLessonInfoLogAop.class);

    @Autowired
    LogFeignClient logFeignClient;
    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    PkLessonInfoMapper pkLessonInfoMapper;

    @AfterReturning(value = "execution(* com.dingup.paike.service.pk.impl.PkLessonInfoServiceImpl.save(..))", returning = "returnValue")
    public void afterSaveLessonLog(JoinPoint joinPoint, PkLessonInfo returnValue) {
        try {
            Object[] obj = joinPoint.getArgs();
            if (obj != null) {
                PkLessonInfoRequestBean bean = (PkLessonInfoRequestBean) obj[0];
                logger.info("保存课节日志 save={}", JSON.toJSONString(bean));
                if (bean.getOperaUserId() != null) {
                    String opearName = userFeignClient.getUserNameByUserId(bean.getOperaUserId());
                }
                LogSaveFeignBean saveBean = new LogSaveFeignBean();
                saveBean.setContent("创建了该课节");
                saveBean.setCreateUserId(bean.getOperaUserId());
                saveBean.setModel(LogModelEnum.PKLESSONINFO);
                saveBean.setModelId(returnValue.getId());
                saveBean.setUpdateType(LogUpdateTypeEnum.ADD);
                logFeignClient.saveLog(saveBean);
                logger.info("保存课节日志 save={}", JSON.toJSONString(bean));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Before(value = "execution(* com.dingup.paike.service.pk.impl.PkLessonInfoServiceImpl.deleteBatchOfLesson(..))")
    public void beforeDeleteLessonLog(JoinPoint joinPoint) {
        try {
            Object[] obj = joinPoint.getArgs();
            if (obj != null) {
                Integer[] lessonIds = (Integer[]) obj[0];
                String operaUserId = (String) obj[1];
                logger.info("删除课节日志 delete={}", JSON.toJSONString(lessonIds));
                for (Integer id : lessonIds) {
                    StringBuffer content = new StringBuffer("删除课程:");
                    PkLessonInfo lessonInfo = pkLessonInfoMapper.selectByPrimaryKey(id);
                    content.append(lessonInfo.getLessonName());
                    LogSaveFeignBean deleteBean = new LogSaveFeignBean();
                    deleteBean.setContent(content.toString());
                    deleteBean.setCreateUserId(operaUserId);
                    deleteBean.setModel(LogModelEnum.PKLESSONINFO);
                    deleteBean.setModelId(id);
                    deleteBean.setUpdateType(LogUpdateTypeEnum.DELETE);
                    logFeignClient.saveLog(deleteBean);
                    logger.info("删除课节日志 delete={}", JSON.toJSONString(lessonInfo));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @AfterReturning(value = "execution(* com.dingup.paike.service.pk.impl.PkLessonInfoServiceImpl.update(..))", returning = "returnValue")
    public void updateLessonLog(JoinPoint joinPoint, PkLessonInfo returnValue) {
        try {
            Object[] obj = joinPoint.getArgs();
            if (obj != null) {
                PkLessonInfoRequestBean bean = (PkLessonInfoRequestBean) obj[0];
                PkLessonInfo pkLessonInfo = bean.getPkLessonInfo();
                PkLessonUpdateLogAdapter adapter = (PkLessonUpdateLogAdapter) returnValue;
                List<String> content = new ArrayList<>();
                content = PkLoggerUtil.getPkLessonDescription(LoggerUtil.getUpdateFileName(pkLessonInfo, adapter.getPkLessonInfo(), PkLessonInfo.class));

                PkLessonUser teacher = adapter.getUpdateTeacher();
                if (teacher != null) {
                    content.add("老师: " + teacher.getUserName());
                }
                Map<String, List<PkLessonUser>> updateStudent = adapter.getUpdateStudent();
                if (updateStudent != null) {
                    List<PkLessonUser> addStudent = updateStudent.get("save");
                    if (!CollectionUtils.isEmpty(addStudent)) {
                        StringBuffer sb = new StringBuffer("添加学生:");
                        String student = addStudent.stream().map(PkLessonUser::getUserName).collect(Collectors.joining(","));
                        sb.append(student);
                        content.add(sb.toString());
                    }
                    List<PkLessonUser> deleteStudent = updateStudent.get("delete");
                    if (!CollectionUtils.isEmpty(deleteStudent)) {
                        StringBuffer sb = new StringBuffer("删除学生:");
                        String student = deleteStudent.stream().map(PkLessonUser::getUserName).collect(Collectors.joining(","));
                        sb.append(student);
                        content.add(sb.toString());
                    }
                }
                Map<String, List<PkLessonUser>> updateObserver = adapter.getUpdateObserver();
                if (updateObserver != null) {
                    List<PkLessonUser> addObsever = updateObserver.get("save");
                    if (!CollectionUtils.isEmpty(addObsever)) {
                        StringBuffer sb = new StringBuffer("添加旁听人:");
                        String observer = addObsever.stream().map(PkLessonUser::getUserName).collect(Collectors.joining(","));
                        sb.append(observer);
                        content.add(sb.toString());
                    }
                    List<PkLessonUser> deleteObsever = updateObserver.get("delete");
                    if (!CollectionUtils.isEmpty(deleteObsever)) {
                        StringBuffer sb = new StringBuffer("删除旁听人:");
                        String observer = deleteObsever.stream().map(PkLessonUser::getUserName).collect(Collectors.joining(","));
                        sb.append(observer);
                        content.add(sb.toString());
                    }
                }

                String contentString = "";
                if (!CollectionUtils.isEmpty(content)) {
                    contentString = content.stream().collect(Collectors.joining("、 "));
                }
                if (!StringUtils.isEmpty(contentString)) {
                    LogSaveFeignBean saveBean = new LogSaveFeignBean();
                    saveBean.setContent(contentString);
                    saveBean.setCreateUserId(bean.getOperaUserId());
                    saveBean.setModel(LogModelEnum.PKLESSONINFO);
                    saveBean.setModelId(returnValue.getId());
                    saveBean.setUpdateType(LogUpdateTypeEnum.UPDATE);
                    logFeignClient.saveLog(saveBean);
                    logger.info("修改课节日志 修改={}", JSON.toJSONString(bean));
                }

                //logFeignClient.saveLog(bean.getOperaUserId(), LogUpdateTypeEnum.ADD, "创建了该科目节", returnValue.getId(), LogModelEnum.PKLESSONINFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
